package com.demo;

import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

/**
 * @author wangfengchen
 * 自定义java请求开发
 * Terminal控制台执行命令：mvn clean package 将target下的jar包放到jmeter lib ext 包下。
 * 然后新建线程添加java请求会自动出现类路径 com.demo.First，选择 Second，添加查看结果树，执行之后可在结果树中看到结果
 */
public class Second implements JavaSamplerClient {

  /**
   * 在图形化界面中显示的变量名称
   */
  private static final String URL_NAME = "URL";

  /**
   * 设置界面中默认显示的变量的值
   */
  private static final String DEFAULT_URL_NAME = "http://www.baidu.com";

  /**
   * 用户输入地址
   */
  private String inputUrl;

  /**
   * 用来存储响应的数据，目的是将响应结果放到查看结果树当中
   */
  private String resultData;


  /**
   * 初始化方法，所有初始化动作都可以在这里写
   *
   * @param javaSamplerContext
   */
  @Override
  public void setupTest(JavaSamplerContext javaSamplerContext) {
    System.out.println("setupTest run");
    inputUrl = javaSamplerContext.getParameter(URL_NAME, DEFAULT_URL_NAME);
    System.out.println("用户输入的url地址是：" + inputUrl);
  }

  /**
   * 实现具体功能逻辑的方法
   *
   * @param javaSamplerContext
   * @return
   */
  @Override
  public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
    System.out.println("runTest run");
    SampleResult sampleResult = new SampleResult();
    StringBuffer sb = new StringBuffer();
    try {
      URL url = new URL(inputUrl);
      URLConnection urlConnection = url.openConnection();
      byte[] buffer = new byte[1024];
      int length;
      // 标记事务的开始
      sampleResult.sampleStart();
      InputStream inputStream = urlConnection.getInputStream();
      while ((length = inputStream.read(buffer)) != -1) {
        resultData = new String(buffer, StandardCharsets.UTF_8);
        sb.append(resultData);
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
//    resultData = "这是响应结果";
    resultData = sb.toString();
    sampleResult.setSampleLabel("自定义java请求访问名称");
    sampleResult.setResponseData(resultData, StandardCharsets.UTF_8.toString());
    sampleResult.setDataType(SampleResult.TEXT);
    // 告诉查看结果树访问是否成功
    sampleResult.setSuccessful(true);
    return sampleResult;
  }

  /**
   * 做收尾工作的方法，比如释放资源
   *
   * @param javaSamplerContext
   */
  @Override
  public void teardownTest(JavaSamplerContext javaSamplerContext) {
    System.out.println("teardownTest run");
  }

  /**
   * 决定在jmeter中要显示哪些属性，第一个执行
   *
   * @return
   */
  @Override
  public Arguments getDefaultParameters() {
    System.out.println("getDefaultParameters run");
    Arguments arguments = new Arguments();
    arguments.addArgument(URL_NAME, DEFAULT_URL_NAME);
    return arguments;
  }

}
